package com.kfm.ding.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kfm.ding.service.ChatService;
import com.kfm.ding.service.DingService;
import com.unfbx.chatgpt.entity.chat.BaseMessage;
import com.unfbx.chatgpt.entity.chat.Message;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
public class DingController {


    @Resource
    ChatService chatService;

    @Resource
    DingService dingService;


    @Resource
    RedisTemplate<String, List<Message>> redisTemplate;

    @RequestMapping("/ding")
    public void dingTalk(@RequestBody String param) {
        log.info("接受到参数{}", param);
        // 格式化参数 获取 问题
        JSONObject json = JSONUtil.parseObj(param);
        String question = json.getJSONObject("text").getStr("content");
        String id = json.getJSONArray("atUsers").getJSONObject(0).getStr("dingtalkId");
        log.info("问题是{}", question);
        // TODO 1. 调用 chatGPT
        // TODO 2. 获取响应的内容
        // TODO 3. 发送给机器人响应给用户
        String content = chatService.ask(question, id);
        // 如果之前还问过问题
        List<Message> messages = redisTemplate.opsForValue().get(id);
        // 问题以及答案的实体
        Message ques = new Message(BaseMessage.Role.USER.getName(), null, question, null, null, null);
        Message cont = new Message(BaseMessage.Role.ASSISTANT.getName(), null, content, null, null, null);
        if (messages == null) {
            messages = new ArrayList<>();
        }
        messages.add(ques);
        messages.add(cont);
        redisTemplate.opsForValue().set(id, messages);

        // 机器人设置的关键词中有chat，表示必须包含chat才能发送成功
        dingService.sendMessage("chat:\n" + content);
    }


}
